import React, { useState } from "react";
import { StyleSheet, Text, View } from "react-native";
import AccountHeader from "./AccountHeader";
import { vh, vw } from "@/common/dimensions";
import InputViewRow from "./InputViewRow";
import TextButton from "../../components/TextButton";
import GlobalModal, { ModalPropsType } from "@/components/GlobalModal";
import { PASSWORD_RULE, USER_NAME } from "@/config/reg";
import { accountLoginServer } from "@/servers/app-servers";
import { router } from "expo-router";
import { useAtom } from "jotai";
import { userInfoAtom } from "@/store/user";
import Storage from "@/utils/Storage";
import { useUserImgList } from "@/hooks/useUserImgList";
import { useResultShow } from "@/hooks/useResultShow";
export default function Login() {
    const [ userInfo ,setUserInfo ] = useAtom(userInfoAtom)
	const [usernameValue, setUsernameValue] = useState<string>("");
	const [passwordValue, setPasswordValue] = useState<string>("");
    const [usernameError, setUsernameError] = useState<string | null>(null); // 用户名错误状态
	const [passwordError, setPasswordError] = useState<string | null>(null); // 密码错误状态
	const [showModal, setShowModal] = useState(false);
    // 使用自定义 Hook  获取用户图片列表
    const { getUserImgList } = useUserImgList();
    // 自定义hook 获取 resultShow
    const { getResultShow } = useResultShow()

	const changeUsername = (value: string) => {
		setUsernameValue(value);
        if (!USER_NAME.test(value)) {
			setUsernameError("用户名应为3-20位的字母或数字");
		} else {
			setUsernameError(null);
		}
        if(!value) setUsernameError(null);
	};

	const changePassword = (value: string) => {
		setPasswordValue(value);
        if (!PASSWORD_RULE.test(value)) {
			setPasswordError("密码应为6-20位，包含字母和数字");
		} else {
			setPasswordError(null);
		}
        if(!value) setPasswordError(null);
	};

	const hideModal = () => {
		setShowModal(false);
	};


    const updateUserInfo = async (userInfo :any) =>{
        setUserInfo(userInfo)
        await Storage.setStorage("uuid" ,userInfo.uuid)
        await Storage.setStorage("userInfo" ,JSON.stringify(userInfo))
        await getResultShow()
        await getUserImgList()
    } 



	const submit = async () => {
        if(!isFormValid){
            setShowModal(true)
            return
        }
        let option = {
            user_name : usernameValue,
            password: passwordValue
        }
        const res = await accountLoginServer(option)
        const { code , data , msg } = res
        if(code !== 0){
            console.log("msg" , msg);
        }else{
            console.log("登录成功" , data.bind_user_info.uuid);
            await updateUserInfo(data.bind_user_info)
        }
	};

    const toRegister = () => {
        router.push('/register')
    }

    
	// 检查表单是否有效
	const isFormValid = !usernameError && !passwordError && usernameValue && passwordValue;

    // 默认弹框数据
    const [modalProps , setModalProps] = useState<ModalPropsType>({
        title: "温馨提示",
        content: `账号应为3-20位的字母或数字;\n密码应为6-20位，包含字母和数字\n请检查输入格式`,
        cancelText: "取消",
        confirmText: "确定",
        onCancel: hideModal,
        onConfirm: hideModal,
        hideModal
    })

	return (
		<View style={styles.loginContainer}>
			<AccountHeader />
			<View style={{ marginTop: 36 }}>
				<InputViewRow
					onChangeText={changeUsername}
					value={usernameValue}
					label="账号"
				/>
                {usernameError && <Text style={styles.errorText}>{usernameError}</Text>}
				<InputViewRow
					onChangeText={changePassword}
					label="密码"
					isPassword={true}
					value={passwordValue}
				/>
                {passwordError && <Text style={styles.errorText}>{passwordError}</Text>}
			</View>
			<View style={styles.buttonLayout}>
                <View>
                    <TextButton
                        backgroundColor="#fff69c"
                        buttonText="登录"
                        onPress={submit}
                        disabled={!isFormValid} // 禁用登录按钮
                    />
                </View>
				<View style={{marginTop:12}}>
                    <TextButton
                        backgroundColor="#f5f4f2"
                        buttonText="注册"
                        onPress={toRegister}
                    />
                </View>
				
			</View>
			<GlobalModal
				visible={showModal}
				modalProps={modalProps}
			/>
		</View>
	);
}

const styles = StyleSheet.create({
	loginContainer: {
		paddingTop: 16 * vw,
		paddingHorizontal: 6 * vw,
		backgroundColor: "#fff",
		height: 100 * vh,
	},
	inputViewRow: {
		borderBottomColor: "#ececec",
		borderBottomWidth: 1,
		marginTop: 12,
		paddingBottom: 10,
	},
	label: {
		fontSize: 15,
		fontWeight: "500",
	},
	input: {
		fontSize: 12,
	},
	buttonLayout: {
		position: "absolute",
		bottom: 30,
		left: 6 * vw,
		width: "100%",
	},
    errorText: {
		color: "red", // 错误提示的红色文字
		fontSize: 10,
	},
});
